package com.hp.java12_springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hp.java12_springsecurity.entity.Permission;
import com.hp.java12_springsecurity.entity.Role;
import com.hp.java12_springsecurity.entity.User;
import com.hp.java12_springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义登录授权逻辑实现
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, s));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询用户的角色
        List<Role> roles = userMapper.selectRolesByUsername(s);
        //查询用户的权限
        List<Permission> permissions = userMapper.selectPermissionsByUsername(s);
        StringBuilder stringBuilder = new StringBuilder();
        roles.forEach(role -> stringBuilder.append("ROLE_" + role.getName()+","));
        permissions.forEach(permission -> stringBuilder.append(permission.getName()+","));
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        //创建Security的User,包装账号、密码和权限
        org.springframework.security.core.userdetails.User user1 =
                new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                        AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString()));
        return user1;
    }
}
